package com.winning.gjhlht.ihe.hl7ClientService.iheResponse;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

import com.winning.common.Constans;
import com.winning.common.data.service.PlatBasicDataService;
import com.winning.common.tools.XMLTool;
import com.winning.core.base.IHEResponseServiceInter;


/**
 * 类名称：ProvideAndRegisterDocumentSetServiceResponse
 * 类描述：   电子健康档案文档注册响应处理结果
 * 创建人：zq
 * 创建时间：2017-1-17 下午1:04:49
 * 修改人：zq
 * 修改时间：2017-1-17 下午1:04:49
 * 修改备注：
 */
public class ProvideAndRegisterDocumentSetServiceResponse implements IHEResponseServiceInter {

    private static Logger LOGGER = Logger.getLogger(Constans.LOG4J_PBS_LOGGER_ID);


    //CDA文档上传返回ID的XPath路径
    private static final String XPATH_RESPONSE_ID = "xsi:Response/@id";

    //CDA文档上传状态XPath路径
    private static final String XPATH_RESPONSE_STATUS = "xsi:Response/@status";

    //CDA文档上传描述细节XPath路径
    private static final String XPATH_RESPONSE_DETAIL = "xsi:Response/xsi:Detail";

    //CDA文档上传响应消息ID
    private static final String XPATH_RESPONSE_OID = "xsi:Id/@extension";

    private static final String XPATH_RESPONSE_DOCUMENTURL = "xsi:Response/@doumentUrl";

    //审计接口返回信息
    Map<String, Object> resultAudit = null;

    @Override
    public Map<String, Object> resonseHandler(PlatBasicDataService platBasicDataService, String responseXMLMessage, Map<String, Object> requestInfoMap, String dataSourseID) {


        //健康档案编号
        String id = requestInfoMap.get("ID").toString();

        LOGGER.info("-->进入CDA文档返回结果处理流程,处理编号:" + id);

        //修改CDA缓存表信息
        String updateSQL = "UPDATE IHE_CDA_DOC_BUFFER SET ";

        updateSQL = readDocumentSetResponseXMLHandler(responseXMLMessage, updateSQL);

        //去除最后一个，
        updateSQL = updateSQL.substring(0, updateSQL.length() - 1);


        //添加修改条件
        updateSQL += "WHERE id = '" + id + "'";

        int result = platBasicDataService.saveCDARegisterResponse(updateSQL, dataSourseID);

        if (result == 1) {
            LOGGER.info("--> CDA文档注册返回结果记录成功");
        } else {
            LOGGER.info("--> CDA文档注册返回结果记录失败");

        }

        return resultAudit;
    }


    /**
     * 解析CDA文档上传返回结果
     * 方法名称: readDocumentSetResponseXMLHandler
     *
     * @param
     * @return HashMap<String   ,   Object>  返回类型说明<br/>
     * @throws <br/>
     * @author lenovo@winning.com.cn<br/>
     * 创建时间：2017-1-20/上午9:04:19<br/>
     */
    private String readDocumentSetResponseXMLHandler(String responseXMLMessage, String updateSQL) {

        //初始化审计接口返回参数
        resultAudit = new HashMap<String, Object>();

        //CDA注册返回文档
        Document document = null;

        try {
            //将返回结果转换成xml文档对象
            document = XMLTool.getDocumentFromXMLString(responseXMLMessage, true);

            if (document != null) {
                //根节点
                Element root = document.getRootElement();

                //获取注册返回结果
                String status = XMLTool.selectAttributeValueByRootElement(root, XPATH_RESPONSE_STATUS);

                if (status != null && !status.equals("")) {
                    //将注册结果写入SQL
                    updateSQL += "ResponseStatus = '" + status + "',";


                    //提供审计接口结果
                    resultAudit.put("RESPONSE_RESULT", status);


                    if (status.equals("AA")) {
                        //注册成功
                        String id = XMLTool.selectAttributeValueByRootElement(root, XPATH_RESPONSE_ID);

                        if (id != null && !id.equals("")) {
                            //将返回结果记录到SQL
                            updateSQL += "RepositoryId = '" + id + "',";
                        }


                        String documentUrl = XMLTool.selectAttributeValueByRootElement(root, XPATH_RESPONSE_DOCUMENTURL);

                        if (documentUrl != null && !documentUrl.equals("")) {
                            updateSQL += "doumentUrl = '" + documentUrl + "',";
                        }

                    } else {
                        //注册失败
                        String detail = XMLTool.selectElementValueByRootElement(root, XPATH_RESPONSE_DETAIL);

                        if (detail != null && !detail.equals("")) {
                            //将返回详细信息记录到SQL
                            updateSQL += "ResponseDetail = '" + detail.replace("'", "") + "',";
                        }
                    }
                }

                //返回消息id
                String responseId = XMLTool.selectAttributeValueByRootElement(root, XPATH_RESPONSE_OID);

                if (responseId != null && !responseId.equals("")) {
                    updateSQL += "ResponseId = '" + responseId + "',";

                }

            }
        } catch (Exception e) {


            e.printStackTrace();
            LOGGER.error(e, e.fillInStackTrace());
        }
        return updateSQL;
    }

}
